<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storagetype">
              <j-dict-select-tag
                style="width: 308.48px"
                type="list"
                v-model="model.storageType"
                dictCode="rk_type"
                placeholder="请选择入库类型"
                :disabledVal="3"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="所属仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouse">
              <erp-warehouse
                ref="erpWarehouse"
                v-model="model.warehouseName"
                @onWarehouseSelected="onWarehouseSelected"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="auditFlowId">
              <j-dict-select-tag
                disabled
                type="list"
                v-model="model.auditFlowId"
                dictCode="business_type"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="上级单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="parentCode">
              <a-input v-model="model.parentCode" placeholder="请输入上级单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageDate">
              <j-date placeholder="请选择入库日期" v-model="model.storageDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-input v-model="model.supplier" disabled placeholder="请输入供应商"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="经办人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dealUser">
              <a-row :gutter="4">
                <a-col :span="18">
                  <a-input v-model="model.dealUsername" placeholder="请选择经办人员"></a-input>
                </a-col>

                <a-col :span="6">
                  <a-button @click="handleSelectEmployee" type="primary" :loading="confirmLoading">选择员工</a-button>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="制单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date placeholder="请选择制单日期" v-model="model.createTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="batchNo">
              <a-input v-model="model.batchNo" placeholder="请输入批次号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="生产车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workshop">
              <a-input v-model="model.workshop" placeholder="请输入生产车间"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customName">
              <a-input v-model="model.customName" disabled placeholder="请输入客户名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="保洁供应商编码"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="bjSupplierCode"
            >
              <a-input v-model="model.bjSupplierCode" placeholder="请输入保洁供应商编码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="保洁供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplierName">
              <a-input v-model="model.bjSupplierName" placeholder="请输入保洁供应商"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="保洁采购单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="bjProcurementCode"
            >
              <a-input v-model="model.bjProcurementCode" placeholder="请输入保洁采购单号" style="width: 250%"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注" style="width: 550%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="五金入库单明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussSparePartStorageDetailTable.loading"
          :columns="bussSparePartStorageDetailTable.columns"
          :dataSource="bussSparePartStorageDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
          :edit-config="editConfig"
          @edit-disabled="editDisabledEvent"
          :row-class-name="rowClassName"
        >
          <template v-slot:toolbarSuffix>
            <a-button @click="addMaterial" v-if="true">新增</a-button>
            <a-button @click="copyDataModal" v-if="true">复制</a-button>
            <a-button @click="pasteData" v-if="true">黏贴</a-button>
            <!--            <a-button @click='' v-show="model.storageType == 0">新增</a-button>-->
            <!--  <a-button @click='addMaterial' >新增</a-button>-->
            <!--            <a-button @click='editMaterial' v-show=" bussStorageDetailTable.dataSource.length > 0 " >编辑</a-button>-->
            <!--          <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增物料</a-button>-->
          </template>
          <template v-slot:erpLocationName="props">
            <tsl-warehouse
              v-model="props.value"
              :disabled="(props.row.isDelete && props.row.isDelete === 1) || formDisabled"
              :rowData="props"
              @handlerOk="warehouseOk"
            ></tsl-warehouse>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <bussiness-type-list ref="bussinessType" @handleOk="bussinessOk" :businessNode="3"></bussiness-type-list>
    <erp-good-list ref="good" @handlerOk="goodOk" checkval="checkbox" :category="3"></erp-good-list>
    <employee-list-modal ref="selectEmployee" @handlerOk="handleSelectEmployeeOk" />
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import moment from 'dayjs'
import { Modal } from 'ant-design-vue'

import TslWarehouse from '@comp/tsl/TslWarehouse.vue'
import ErpGoodList from '@/views/modules/goods/ErpGoodsListModal'
import BussinessTypeList from '@/views/modules/business/BusinessTypeList'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'

export default {
  name: 'BussSparePartStorageForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    BussinessTypeList,
    ErpGoodList,
    TslWarehouse,
    EmployeeListModal,
  },
  data() {
    return {
      moment,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        id: '',
        code: '',
        storageType: '',
        warehouse: '',
        warehouseName: '',
        auditFlowId: '',
        parentCode: '',
        storageDate: '',
        supplier: '',
        dealUser: '',
        dealUsername: '',
        createTime: '',
        batchNo: '',
        workshop: '',
        customName: '',
        bjSupplierName: '',
        bjSupplierCode: '',
        bjProcurementCode: '',
        remark: '',
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {},
      tableRef: '',
      refKeys: ['bussSparePartStorageDetail'],
      tableKeys: ['bussSparePartStorageDetail'],
      activeKey: 'bussSparePartStorageDetail',
      // 成品入库单明细
      bussSparePartStorageDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编号',
            key: 'materialCode',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '客户物料编号',
            key: 'customerMaterialCode',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料id',
            key: 'materialId',
            type: JVXETypes.hidden,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '数量',
            key: 'num',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助单位',
            key: 'supportUnit',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助数量',
            key: 'supportNum',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库位',
            key: 'erpLocationId',
            type: JVXETypes.slot,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            slotName: 'erpLocationName',
          },
          {
            title: '物料批号',
            key: 'materialLotnumber',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '限用日期',
            key: 'expiredDate',
            type: JVXETypes.date,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '生产日期',
            key: 'createDate',
            type: JVXETypes.date,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '质检状态',
            key: 'status',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '成品入库单id',
            key: 'sparePartId',
            type: JVXETypes.hidden,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/business/bussSparePartStorage/add',
        edit: '/business/bussSparePartStorage/edit',
        queryById: '/business/bussSparePartStorage/queryById',
        bussSparePartStorageDetail: {
          list: '/business/bussSparePartStorage/queryBussSparePartStorageDetailByMainId',
        },
      },
      num: 1,
      copydata: {},
      editConfig: { trigger: 'click', mode: 'cell', showStatus: true, activeMethod: this.activeRowMethod },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  mounted() {
    this.getAllTable().then((tables) => {
      this.tableRef = tables[0]
    })
    setTimeout(() => {
      if (!this.model.id) {
        let rows = this.tableRef.getNewDataWithId()
        this.tableRef.removeRowsById(rows[0].id)
      }
    }, 100)
  },
  methods: {
    //选择员工方法
    handleSelectEmployeeOk(data) {
      console.log('选择员工：', data)
      if (data) {
        console.log(data);
        // console.log(data.employeeName);
        this.model.dealUser = data.employee
          this.model.dealUsername = data.employeeName
        
        this.$forceUpdate() //重新渲染UI
        // console.log(data.employeeName,this.model.owner);
      }
    },
    //仓库选择
    onWarehouseSelected(rows) {
      this.model.warehouse = rows.code
      this.model.warehouseName = rows.name
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectEmployee.visible = true
    },
    rowClassName({ row, rowIndex }) {
      // 根据行数据动态返回 CSS 类名
      if (row.isDelete && row.isDelete === 1) {
        return 'frozen-row'
      }
      // 默认情况下不设置特定背景色
      return ''
    },
    editDisabledEvent({ row, column }) {
      alert('禁止编辑')
    },
    activeRowMethod({ row, column }) {
      if (row.isDelete && row.isDelete == 1) {
        return false
      }
      // 自定义禁用编辑的逻辑，返回 true 表示禁用编辑
      return true // 示例：禁用 disabled 字段为 true 的行，以及 gender 列
    },
    copyDataModal() {
      // 复制数据
      let rows = this.tableRef.selectedRows
      if (rows.length === 0 || rows.length > 1) {
        this.$message.warn('请选择一条入库信息！')
        return
      }
      let _this = this
      Modal.confirm({
        title: () => '复制数据',
        content: () => (
          <div>
            <a-space>
              <span>复制行数</span>
              <a-input-number
                v-model={this.num}
                min={1}
                max={10}
                step={1}
                precision={1}
                formatter={this.formatInteger}
                parser={this.parseInteger}
              />
            </a-space>
          </div>
        ),
        onOk() {
          _this.copyData()
        },
        onCancel() {},
      })
    },
    formatInteger(value) {
      if (value === '') return ''
      const intValue = parseInt(value, 10)
      return isNaN(intValue) ? '' : String(intValue)
    },
    parseInteger(value) {
      return parseInt(value, 10)
    },
    copyData() {
      this.copydata = this.tableRef.selectedRows[0]
    },
    pasteData() {
      // 黏贴数据
      for (var i = 0; i < this.num; i++) {
        let data = { ...this.copydata }
        data.id = ''
        data.rowNum = this.getRowNum()
        if (i !== 0) {
          data.num = 0
        }
        console.log(data)
        this.bussSparePartStorageDetailTable.dataSource.push(data)
      }
      this.bussSparePartStorageDetailTable.dataSource.map((item) => {
        if (item.rowNum == this.copydata.rowNum) {
          item.isDelete = 1
        }
      })
      // console.log(this.bussSparePartStorageDetailTable.dataSource)
    },
    warehouseOk({ result, row }) {
      this.bussSparePartStorageDetailTable.dataSource.forEach((item) => {
        if (item.materialId == row.materialId && item.rowNum == row.rowNum) {
          item.erpLocationId = result.id
          item.erpLocationName = result.name
          item.erpLocationCode = result.code
          item.erpWarehouseName = result.warehouseName
          item.erpWarehouseCode = result.warehouseCode
        }
      })
      this.tableRef.resetScrollTop()
    },
    goodOk(rows) {
      let _this = this
      rows.forEach((item, index) => {
        let obj = {
          materialId: item.id,
          materialName: item.name,
          materialCode: item.code,
          noticeDetailId: item.id,
          spec: item.noneSpec,
          rowNum: this.getRowNum(),
          storageType: this.model.storageType,
          materialTypeName: item.categoryCodeText.split(' ')[0],
          warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
        }
        this.bussSparePartStorageDetailTable.dataSource.push(obj)
      })
      // this.formatterDatas();
    },
    addMaterial() {
      this.$nextTick(() => {
        this.$refs.good.add()
      })
    },
    bussinessOk({ rows, callback }) {
      const row = rows[0]
      this.$set(this.model, 'businessNode', row.businessNode)
      this.$set(this.model, 'materialTypeName', row.materialTypeName)
      this.$set(this.model, 'businessType', row.businessType)
      this.$set(this.model, 'materialTypeCode', row.materialTypeCode)
      callback(true)
    },
    onSearchBussiness() {
      this.$nextTick(() => {
        this.$refs.bussinessType.add()
      })
    },
    addBefore() {
      this.bussSparePartStorageDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.bussSparePartStorageDetail.list, params, this.bussSparePartStorageDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussSparePartStorageDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    getRowNum() {
      let source = this.bussSparePartStorageDetailTable.dataSource
      if (source.length === 0) {
        return '0001'
      }
      let { rowNum } = source[source.length - 1]
      let nextRowNum = Number(rowNum) + 1
      if (nextRowNum < 10) {
        return '000' + nextRowNum
      } else if (nextRowNum < 100) {
        return '00' + nextRowNum
      } else if (nextRowNum < 1000) {
        return '0' + nextRowNum
      } else {
        return String(nextRowNum)
      }
    },
  },
}
</script>

<style scoped>
</style>
<style>
.frozen-row {
  background-color: #eaf2fd; /* 更深的背景色 */
  font-weight: bold;
  color: #333; /* 可能需要调整文字颜色以提高对比度 */
}
.anticon-question-circle {
  display: none !important; /* 隐藏默认图标 */
}
</style>